from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
import socket

class CSVNotExistError(Exception):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        try:
            with open('out.csv', 'r') as f:
                self.send_response(200)
                self.send_header("Content-type", "text/csv")
                self.send_header("Content-Disposition", "attachment; filename=out.csv")
                self.end_headers()
                self.wfile.write(f.read())
        except IOError:
            raise CSVNotExistError('out.csv not exist')

def run_server(port=8080):
    try:
        server = HTTPServer(('', port), Handler)
        print "http://%s:%s" % (socket.gethostbyname_ex(socket.gethostname())[2][0],port)
        server.serve_forever()
    except KeyboardInterrupt:
        print " received, shutting down server"
        server.socket.close()

if __name__ == '__main__':
    run_server()
